package com.czy.owner.ui.garage;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.czy.otherlib.swipetoloadlayout.OnRefreshListener;
import com.czy.otherlib.swipetoloadlayout.SwipeToLoadLayout;
import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.GarageCarAdapter;
import com.czy.owner.api.DefaultCarApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.rxbus.CarEvent;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.disk.DiskLruCacheHelper;
import com.czy.owner.widget.PageTitleView;
import com.czy.owner.widget.UniversalDialog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.czy.owner.ui.store.OnLineOrderActivity2.REQUEST_CAR;

/**
 * Created by King on 2016/6/6 0006.
 */
public class MyGarageActivity extends BaseActivity implements OnRefreshListener {
    private final String TAG = getClass().getSimpleName();
    private PageTitleView pageTitle;
    @BindView(R.id.ll_garage_add)
    LinearLayout llAdd;
    @BindView(R.id.ll_garage_add_wrapper)
    LinearLayout llAddWrapper;
    @BindView(R.id.ll_garage_none)
    LinearLayout llNoneTips;
    @BindView(R.id.ll_garage_full_wrapper)
    LinearLayout llFullWrapper;
    @BindView(R.id.swipeToLoadLayout)
    SwipeToLoadLayout swipeToLoadLayout;

    @BindView(R.id.refresh_target)
    RecyclerView recyclerView;

    private GarageCarAdapter mAdapter;
    private DiskLruCacheHelper cacheHelper;

    private boolean noteditable;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_my_garage;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        noteditable = getIntent().getBooleanExtra("noteditable", false);
        try {
            cacheHelper = new DiskLruCacheHelper(MyGarageActivity.this);
        } catch (IOException e) {
            e.printStackTrace();
        }
        pageTitle = new PageTitleView((RelativeLayout) findViewById(R.id.rl_page_title), getResources().getString(R.string.my_garage), true);
        initAdapter();
        initListener();
        swipeToLoadLayout.setRefreshing(true);
    }

    @Override
    protected void updateViews() {

    }

    private void initAdapter() {
        mAdapter = new GarageCarAdapter(this, UserHelper.getInstance().getCarInfoList());
        mAdapter.setNoteditable(noteditable);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mAdapter);
        swipeToLoadLayout.setOnRefreshListener(this);
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<CarInfo>() {
            @Override
            public void onItemClick(int position, CarInfo o, View view) {
                if (noteditable) {
                    Intent intent = new Intent();
                    intent.putExtra("carInfo", o);
                    setResult(REQUEST_CAR, intent);
                    finish();
                }
                //Toast.makeText(MyGarageActivity.this, "OnClick:" + ((CarInfo) o).getChName(), Toast.LENGTH_SHORT).show();
            }
        });
        mAdapter.setOnItemSetDefaultListener(new GarageCarAdapter.OnItemSetDefaultListener() {
            @Override
            public void onSet(CarInfo mCarInfo, final int position) {
                DefaultCarApi mApi = new DefaultCarApi(new HttpOnNextListener<String>() {
                    @Override
                    public void onNext(String o) {
                        for (int i = 0; i < UserHelper.getInstance().getCarInfoList().size(); i++) {
                            UserHelper.getInstance().getCarInfoList().get(i).setDefault(false);
                        }
                        UserHelper.getInstance().getCarInfoList().get(position).setDefault(true);
                        RxBus.getDefault().post(new CarEvent());

                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        e.printStackTrace();
                        Toast.makeText(MyGarageActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }, MyGarageActivity.this);


                HashMap<String, Object> requestMap = new HashMap<>();
                requestMap.put("session", UserHelper.getInstance().getSessionInfoModel(MyGarageActivity.this).getSession());
                requestMap.put("ownerCarId", mCarInfo.getOwnerCarId());

                mApi.setMap(requestMap);
                HttpManager.getInstance().doHttpDeal(mApi);

            }
        });
        mAdapter.setOnItemEditListener(new GarageCarAdapter.OnItemEditListener() {
            @Override
            public void onEdit(CarInfo mCarInfo) {
                Intent intent = new Intent(MyGarageActivity.this, EditCarActivity.class);
                intent.putExtra(EditCarActivity.ACTION_TYPE_KEY, EditCarActivity.ACTION_TYPE.MODIFY);
                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, mCarInfo);
                startActivityForResult(intent, 2);
            }
        });
        mAdapter.setOnItemDeleteListener(new BaseRecyclerAdapter.OnItemDeleteListener<CarInfo>() {
            @Override
            public void onItemDelete(final int position, final CarInfo o, View view) {
                new UniversalDialog(MyGarageActivity.this).builder().setTitle("确定删除车辆")
                        .setMsg("确定删除该车辆,删除后不可恢复!")
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                mLoadView.ShowLoadView("正在删除");
                                RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CAR_DELETE);
                                params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(MyGarageActivity.this).getSession());
                                params.addBodyParameter("ownerCarId", "" + o.getOwnerCarId());
                                x.http().post(params, new Callback.CommonCallback<String>() {
                                    @Override
                                    public void onSuccess(String result) {
                                        String data = PhoneUtils.checkResponseFlag(MyGarageActivity.this, result);
                                        if (data != null) {
                                            PhoneUtils.ShowToastMessage(MyGarageActivity.this, "车辆删除成功");
                                            UserHelper.getInstance().getCarInfoList().remove(position);
                                            mAdapter.removeCar(position);
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable ex, boolean isOnCallback) {
                                        PhoneUtils.ShowToastMessage(MyGarageActivity.this, "数据提交异常,请重试");
                                    }

                                    @Override
                                    public void onCancelled(CancelledException cex) {

                                    }

                                    @Override
                                    public void onFinished() {
                                        checkTips();
                                        mLoadView.CancleLoadView();
                                    }
                                });
                            }
                        }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).show();

            }
        });
    }

    private void initListener() {
        pageTitle.getLeftButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        llAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MyGarageActivity.this, PickBrandActivity.class);
                // 新增车辆无需立即返回
                intent.putExtra(PickBrandActivity.START_FLAG, 0);
                startActivityForResult(intent, 1);
            }
        });
    }


    private void getData() {

        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CARS);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(MyGarageActivity.this, result);
                List<CarInfo> dataList = new ArrayList<CarInfo>();
                if (data != null) {
                    if (cacheHelper != null) {
                        cacheHelper.put(UserHelper.getInstance().getUserAccount() + "garage_info", data);
                    }
                    UserHelper.getInstance().getCarInfoList().clear();
                    try {
                        Gson gson = new GsonBuilder().create();
                        dataList = gson.fromJson(data, new TypeToken<List<CarInfo>>() {
                        }.getType());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    UserHelper.getInstance().setCarInfoList(dataList);
                    mAdapter.setList(UserHelper.getInstance().getCarInfoList());
                    checkTips();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                swipeToLoadLayout.setRefreshing(false);
            }
        });


    }

    @Override
    public void onRefresh() {
        getData();
    }

    private void checkTips() {
        if (mAdapter.getItemCount() >= 5) {
            llNoneTips.setVisibility(View.GONE);
            llAddWrapper.setVisibility(View.VISIBLE);
            llFullWrapper.setVisibility(View.GONE);
        } else if (mAdapter.getItemCount() > 0) {
            llNoneTips.setVisibility(View.GONE);
            llAddWrapper.setVisibility(View.VISIBLE);
            llFullWrapper.setVisibility(View.GONE);
        } else {
            llNoneTips.setVisibility(View.VISIBLE);
            llAddWrapper.setVisibility(View.VISIBLE);
            llFullWrapper.setVisibility(View.GONE);
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Constants.ACTIVITY_RESULT_CODE_CAR_ADD) {
            swipeToLoadLayout.setRefreshing(true);
        } else if (requestCode == 2) {
            getData();
        }
    }
}
